<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="renderer" content="webkit">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  <link rel="stylesheet" href="../../../lib/layui/css/layui.css" media="all">
  <link href="../../../lib/wangeditor/style.css" rel="stylesheet">
  <link href="../../../css/layout.css" rel="stylesheet">
  <link rel="stylesheet" href="../../../css/public.css" media="all">
  <style>
      body {
          background-color: #ffffff;
      }
  </style>
</head>
<body>
<form class="layui-form" action="" lay-filter="demo-val-filter">
  <div class="layui-form layuimini-form" id="myForm">
    <div class="layui-form-item">
      <label class="layui-form-label required">通知名称</label>
      <div class="layui-input-block">
        <input type="text" name="name" lay-verify="required" placeholder="请输入" value="" class="layui-input">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">通知内容</label>
      <div id="editor—wrapper">
        <div id="toolbar-container"><!-- 工具栏 --></div>
        <div id="editor-container"><!-- 编辑器 --></div>
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">置顶</label>
      <div class="layui-input-block">
        <input type="checkbox" name="topFlag" lay-skin="switch" lay-filter="topFlag" lay-text="是|否">
      </div>
    </div>
    <div class="layui-form-item">
      <label class="layui-form-label">添加时间</label>
      <div class="layui-input-block">
        <input class="layui-input" name="createDate" style="width: 220px" id="createDate" placeholder="请选择">
      </div>
    </div>
    <div class="layui-form-item" style="margin-top: 24px">
      <label class="layui-form-label">附件</label>
      <div class="layui-upload" style="margin-left: 150px">
        <button type="button" class="layui-btn" id="files-table">选择文件</button>
        <div class="layui-upload-list">
          <table class="layui-table">
            <colgroup>
              <col style="min-width: 100px;">
              <col width="150">
              <col width="260">
              <col width="150">
            </colgroup>
            <thead>
            <th>文件名</th>
            <th>大小</th>
            <th>上传进度</th>
            <th>操作</th>
            </thead>
            <tbody id="files-list"></tbody>
          </table>
        </div>
        <button type="button" class="layui-btn" id="files-action">上传</button>
      </div>
    </div>

    <hr/>

    <div class="layui-form-item">
      <div class="layui-input-block">
        <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn" type="button">保存</button>
      </div>
    </div>
  </div>
</form>

<script src="../../../lib/layui/layui.js" charset="utf-8"></script>
<script src="../../../lib/wangeditor/index.js"></script>
<script src="../../../api/common.js" charset="utf-8"></script>

<script>
  layui.use(['form', 'laydate'], function () {
    var form = layui.form,
      layer = layui.layer,
      laydate = layui.laydate;
    $ = layui.$;
    var element = layui.element;
    var fileList = []
    var content = ''

    function getQueryString(name) {
      var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
      var r = window.location.search.substr(1).match(reg);
      if (r != null) {
        return decodeURIComponent(r[2]);
      }
      return null;
    }

    // 获取参数
    var id = getQueryString('id');

    laydate.render({
      elem: '#createDate',
      type: 'datetime',
      fullPanel: true // 2.8+
    });

    $.ajax({
      type: 'GET',
      url: local + 'notice/get/' + id,
      // data: JSON.stringify(),
      dataType: "json",
      headers: {
        // 'content-type': 'application/json;charset=UTF-8',
        'Authorization': `Bearer ${ localStorage.getItem("token") }`,
      },
      contentType: 'application/json;charset=UTF-8',
      success: function (res) {
        // orgShowId = res.data.orgId
        // roleShowId = res.data.roleList[0].roleId
        if (res.code === 200) {
          console.log('res', res)
          form.val('demo-val-filter', {
            'name': res.data.name,
            'createDate': res.data.createDate,
            'username': res.data.username,
          });
          form.render('select')
          editor.setHtml(res.data.content)
          var that = this;
          var elemList = $('#files-list')
          // 读取本地文件
          var l = res.data?.attachmentList?.length
          for (var i = 0; i < l; i++) {
            fileList.push(res.data?.attachmentList[i].attachmentId)
            var tr = $(['<tr id="upload-' + i + '">',
              '<td>' + res.data?.attachmentList[i].fileName + '</td>',
              '<td id="id" style="display: none"></td>',
              '<td>-</td>',
              '<td>-</td>',
              '<td>',
              '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
              '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete"  key-index="'+ res.data?.attachmentList[i].attachmentId +'" type="button">删除</button>',
              '</td>',
              '</tr>'].join(''));
            elemList.append(tr);
            tr.find('.demo-delete').on('click', function (e) {
              // delete files[index]; // 删除对应的文件
              console.log($(this).attr('key-index'))
              console.log('asdf',e)
              var id = $(this).attr('key-index')

              console.log('id',id)

              fileList = fileList.filter(function(item) {
                return item !== id
              });
              console.log('fileList', fileList)
              $(this).parent().parent().remove()
              // e.remove()
              // $('#files-list').children('tr').eq($(this).attr('key-index')).remove();
              // tr.eq().remove();
              // tr.remove(); // 删除表格行
              // 清空 input file 值，以免删除后出现同名文件不可选
              // uploadListIns.config.elem.next()[0].value = '';
            });

          }
          // res.data.attachmentList(function (index, file, result) {
          //   var tr = $(['<tr id="upload-' + index + '">',
          //     '<td>' + file.name + '</td>',
          //     // '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
          //     '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
          //     '<td>',
          //     '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
          //     '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
          //     '</td>',
          //     '</tr>'].join(''));
          //
          //   // 单个重传
          //   // tr.find('.demo-reload').on('click', function () {
          //   //   obj.upload(index, file);
          //   // });
          //
          //   // 删除

          //
          //   that.elemList.append(tr);
          //   element.render('progress'); // 渲染新加的进度条组件
          // });


          // editor.txt.html(res.data.content)
          // content = res.data.content
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, {icon: 5});
      }
    });


    layui.use(function () {
      var upload = layui.upload;

      var $ = layui.$;

      // 制作多文件上传表格
      var uploadListIns = upload.render({
        elem: '#files-table',
        elemList: $('#files-list'), // 列表元素对象
        url: local + 'attachment/upload', // 实际使用时改成您自己的上传接口即可。
        accept: 'file',
        multiple: true,
        data: {
          objType: 1,
        },
        headers: {
          'Authorization': `Bearer ${ localStorage.getItem("token") }`,
        },
        number: 3,
        auto: false,
        bindAction: '#files-action',
        choose: function (obj) {
          var that = this;
          var files = this.files = obj.pushFile(); // 将每次选择的文件追加到文件队列
          // 读取本地文件
          obj.preview(function (index, file, result) {
            var tr = $(['<tr id="upload-' + index + '">',
              '<td>' + file.name + '</td>',
              '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>',
              '<td><div class="layui-progress" lay-filter="progress-demo-' + index + '"><div class="layui-progress-bar" lay-percent=""></div></div></td>',
              '<td>',
              '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>',
              '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>',
              '</td>',
              '</tr>'].join(''));

            // 单个重传
            tr.find('.demo-reload').on('click', function () {
              obj.upload(index, file);
            });

            // 删除
            tr.find('.demo-delete').on('click', function () {
              delete files[index]; // 删除对应的文件
              tr.remove(); // 删除表格行
              // 清空 input file 值，以免删除后出现同名文件不可选
              uploadListIns.config.elem.next()[0].value = '';
            });

            that.elemList.append(tr);
            element.render('progress'); // 渲染新加的进度条组件
          });
        },
        done: function (res, index, upload) { // 成功的回调
          console.log('res', res)
          fileList.push(res.data.attrId)

          var that = this;
          // if(res.code == 0){ // 上传成功
          var tr = that.elemList.find('tr#upload-' + index)
          var tds = tr.children();
          tds.eq(3).html(''); // 清空操作
          delete this.files[index]; // 删除文件队列已经上传成功的文件
          return;
          //}
          this.error(index, upload);
        },
        allDone: function (obj) { // 多文件上传完毕后的状态回调
          console.log(obj)
        },
        error: function (index, upload) { // 错误回调
          var that = this;
          var tr = that.elemList.find('tr#upload-' + index);
          var tds = tr.children();
          // 显示重传
          tds.eq(3).find('.demo-reload').removeClass('layui-hide');
        },
        progress: function (n, elem, e, index) { // 注意：index 参数为 layui 2.6.6 新增
          element.progress('progress-demo-' + index, n + '%'); // 执行进度条。n 即为返回的进度百分比
        }
      });
    });

    //监听提交
    form.on('submit(saveBtn)', function (data) {
      var obj = data.field
      console.log('fileList', fileList)

      obj.attIdList = fileList
      obj.status = 2
      obj.content = editor.getHtml()

      // obj.topFlag = obj.topFlag === 'on'

      // console.log('html', editor.getHtml())

      if (obj.topFlag) {
        obj.topFlag = true
      } else {
        obj.topFlag = false
      }
      obj.id = id
      console.log('obj', obj)
      $.ajax({
        type: 'POST',
        url: local + 'notice/update',
        data: JSON.stringify(obj),
        dataType: "json",
        headers: {
          'Authorization': `Bearer ${ localStorage.getItem("token") }`,
        },
        contentType: 'application/json;charset=UTF-8',
        success: function (res) {//res为相应体,function为回调函数
          console.log('data', res)
          if (res.code === 200) {
            // layer.alert('添加成功');
            var iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
            parent.layui.table.reload('currentTableId');
            return false;
          }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          layer.alert('操作失败！！！' + XMLHttpRequest.status + "|" + XMLHttpRequest.readyState + "|" + textStatus, {icon: 5});
        }
      });
    });

    var {createEditor, createToolbar} = window.wangEditor

    var editorConfig = {
      placeholder: '请输入',
      MENU_CONF: {
        uploadImage: {
          server: local + 'attachment/upload',
          maxFileSize: 10 * 1024 * 1024,
          // 最多可上传几个文件，默认为 100
          maxNumberOfFiles: 100,
          allowedFileTypes: [],
          // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
          fieldName: "file",
          headers: {
            Authorization: `Bearer ${ localStorage.getItem("token") }`,
          },
          meta: {
            objType: 2
          },
          metaWithUrl: false,
          withCredentials: false,
          // 超时时间，默认为 10 秒
          timeout: 5 * 1000, // 5 秒

          // 单个文件上传失败
          onFailed(file, res, error) {
            // TS 语法
            // onFailed(file, res) {           // JS 语法
            console.log(`${ file.name } 上传失败`, res);
            console.log("error", error);
            // Message.error("上传失败，图片不能超过4M");
          },

          // 上传错误，或者触发 timeout 超时
          onError(file, err, res) {
            console.log(`${ file.name } 上传出错`, err, res);
            // Message.error("上传失败，图片不能超过4M");
          },
        },
        uploadVideo: {
          server: local + 'attachment/upload',
          maxFileSize: 500 * 1024 * 1024,
          maxNumberOfFiles: 100,
          allowedFileTypes: [],
          // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
          fieldName: "file",
          headers: {
            Authorization: `Bearer ${ localStorage.getItem("token") }`,
          },
          meta: {
            objType: 1
          },
          // 将 meta 拼接到 url 参数中，默认 false
          metaWithUrl: false,
          // 跨域是否传递 cookie ，默认为 false
          withCredentials: false,
          // 超时时间，默认为 10 秒
          timeout: 5 * 1000, // 5 秒

          // 单个文件上传失败
          onFailed(file, res, error) {
            // TS 语法
            // onFailed(file, res) {           // JS 语法
            console.log(`${ file.name } 上传失败`, res);
            console.log("error", error);
          },

          // 上传错误，或者触发 timeout 超时
          onError(file, err) {
            if (err.include('maximum')) {
              // Message.error("上传失败,文件过大");
              console.log("上传失败,文件过大");
            } else {
              console.log("上传失败");
              // Message.error("上传失败");
            }
          },
        },
      },
      onChange(editor) {
        const html = editor.getHtml()
        // console.log('editor content', html)
        // 也可以同步到 <textarea>
      }
    }

    var editor = createEditor({
      selector: '#editor-container',
      html: '<p><br></p>',
      content: [
        {
          type: 'paragraph',
          lineHeight: '1.5',
          children: [
            {text: '', fontFamily: '仿宋', fontSize: '22px'},
          ]
        },
      ],
      config: editorConfig,
      mode: 'default', // or 'simple'

    })

    var toolbarConfig = {
      excludeKeys: ["insertImage", "insertVideo"],
    }

    var toolbar = createToolbar({
      editor,
      selector: '#toolbar-container',
      config: toolbarConfig,
      mode: 'default', // or 'simple'，

    })
  });
</script>
</body>
</html>
